import os, shutil, time, sys
import os.path as op
from fnmatch import fnmatch
from subprocess import Popen
from configobj import ConfigObj

def create_app(debug=False):
    try:
        _create_app(debug)
    except:
        import traceback
        traceback.print_exc()
        raw_input('\nPress ENTER to continue...\n')
        sys.exit(1)

def run(debug=False):
    cwd = os.getcwd()
    
    if debug:
        os.chdir('debug')
        pid = Popen(["xulrunner", "application.ini", "-jsconsole"]).pid
    else:
        os.chdir('dist')
        pid = Popen(["xulrunner", "application.ini"]).pid
    
    os.chdir(cwd)
    
def _create_app(debug):
    rootDir = 'debug' if debug else 'dist'
    
    if not op.exists(rootDir+'/chrome/content'):
        os.makedirs(rootDir+'/chrome/content')

    if not op.exists(rootDir+'/defaults/preferences'):
        os.makedirs(rootDir+'/defaults/preferences')

    create_ini(rootDir)
    create_prefs_js(debug, rootDir)
    open(rootDir+'/chrome/chrome.manifest', 'w').write('content app file:content/')

    # Copy XUL, JS, and CSS files:
    copy_files('src/*.xul', rootDir+'/chrome/content')
    copy_files('src/*.js', rootDir+'/chrome/content')
    copy_files('src/*.css', rootDir+'/chrome/content')

def create_ini(rootDir):
    text = open('src/application.ini').read().strip()
    buildId = time.strftime("%Y%m%d")

    fout = open(rootDir+'/application.ini', 'w')
    fout.write(text + '\nBuildID=' + buildId)    
    fout.close()

def create_prefs_js(debug, rootDir):
    fout = open(rootDir+'/defaults/preferences/prefs.js', 'w')
    fout.write('pref("toolkit.defaultChromeURI", "chrome://app/content/app.xul");\n')

    if op.exists("src/prefs.ini"):
        cfg = ConfigObj("src/prefs.ini")
        for item in cfg.items():
            fout.write('pref("%s", "%s");\n' % item)
    
    if debug:
        fout.write("""

/* debugging prefs */
pref("browser.dom.window.dump.enabled", true);
pref("javascript.options.showInConsole", true);
pref("javascript.options.strict", true);
pref("nglayout.debug.disable_xul_cache", true);
pref("nglayout.debug.disable_xul_fastload", true);""")

    fout.close()

def copy_files(src, dest):
    root, glob = op.split(src)
    files = (op.join(root, f) for f in os.listdir(root) if fnmatch(f, glob))
    for f in files:
        shutil.copy(f, dest)

if __name__ == '__main__':
##    create_app(
##        Name='Test App',
##        Vendor='Feihong Hsu',
##        Version='1.0',
##        BuildID='20070412',
##        Copyright='Copyright (c) 2008 Feihong Hsu',
##        ID='testapp@feihonghsu.com',
##        MinVersion='1.9pre',
##        MaxVersion='1.9.0.*',
##    )
    pass
